<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :minSearchLabelWidth="102"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="tableData"
        @add="operateHandle($event, 'add')"
        @exprot="operateHandle($event, 'exprot')"
        @remove="operateHandle($event, 'remove')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @view="operateHandle($event, 'view')"
        @enable="operateHandle($event, 'enable')"
        @unEnable="operateHandle($event, 'unEnable')"
        @rowEnable="operateHandle($event, 'rowEnable')"
        @rowUnEnable="operateHandle($event, 'rowUnEnable')"
      />
    </div>

    <TrEditPopup
      :width="980"
      v-model="isShowEdit"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :labelWidth="112"
      :list="popupList"
      :relationList="relationList"
      @close="isShowEdit = false"
      @confrim="editConfirmHandle"
    />

    <TrDetail
      v-model="isShowDetailPopup"
      :leftList="detailList"
      statusModel="hidden"
      :detailData="detailData"
      :isNeedFooter="false"
      :labelWidth="114"
      @close="closeDetailPopup"
    />
  </div>
</template>

<script>
import { getColor } from "@/utils/billColor";
import enumData from "@/utils/enumCode.js";
import {
  getList,
  // getDetail,
  add,
  remove,
  update,
  updateStatus,
} from "@/api/baseCode/deviceLedger";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";

export default {
  components: {
    TrTable,
    TrEditPopup,
    TrDetail,
  },
  name: "DeviceLedger",
  data: () => ({
    tableColumn: [
      {
        type: "text",
        label: "系统资产编码",
        value: "systemAssetsCode",
      },
      {
        type: "text",
        label: "设备名称",
        value: "assetsModelName",
      },
      {
        type: "text",
        label: "所属品牌",
        value: "assetsBrandName",
      },
      {
        type: "text",
        label: "资产型号编码",
        value: "assetsModelCode",
      },
      {
        type: "text",
        label: "设备编号",
        value: "deviceCode",
      },
      {
        type: "text",
        label: "设备分类",
        value: "deviceType",
      },
      {
        type: "text",
        label: "所有权人",
        value: "ownerUserName",
      },
      {
        type: "text",
        label: "机台号",
        value: "machineCode",
      },
      {
        type: "text",
        label: "设备铭牌编号",
        value: "deviceNameplateCode",
      },
      {
        type: "text",
        label: "资产种类",
        value: "assetsType",
      },
      {
        type: "text",
        label: "计量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "购置时间",
        value: "buyTime",
      },
      {
        type: "text",
        label: "使用部门",
        value: "usingDeptName",
      },
      {
        type: "text",
        label: "使用部门负责人",
        value: "usingHeadName",
      },
      {
        type: "text",
        label: "制程",
        value: "processName",
      },
      {
        type: "text",
        label: "使用项目",
        value: "useProject",
      },
      {
        type: "text",
        label: "存放位置",
        value: "placementLocation",
      },
      {
        type: "text",
        label: "资产管理员",
        value: "assetAdminUserName",
      },
      {
        type: "text",
        label: "设备状况",
        value: "isEnabledName",
      },
      {
        type: "text",
        label: "闲置原因",
        value: "idleReason",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "view",
          },
          {
            label: "编辑",
            option: "rowEdit",
          },
        ],
      },
    ],
    searchHideList: [
      {
        id: "systemAssetsCode",
        type: "input",
        width: 33.33,
        label: "系统资产编码",
        value: "",
      },
      {
        id: "assetsModelId",
        type: "loadselect",
        width: 33.33,
        label: "设备名称",
        value: "",
        requestObj: {
          url: "/api/mes-equipment-service/assets-mode/page",
          method: "post",
          searchKey: "assetsModeName",
          rlLabel: "assetsModeName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "assetsBrandId",
        type: "loadselect",
        width: 33.33,
        label: "所属品牌",
        value: "",
        list: [],
        requestObj: {
          url: "/api/mes-equipment-service/assets-brand/rpc-page",
          method: "post",
          searchKey: "brandName",
          rlLabel: "brandName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "machineCode",
        type: "input",
        width: 33.33,
        label: "机台号",
        value: "",
      },
      {
        id: "isEnabledList",
        type: "multiSelect",
        list: [],
        width: 33.33,
        label: "设备状态",
        value: [],
      },
      {
        startStr: "updateTimeStart",
        endStr: "updateTimeEnd",
        id: "modifyTime",
        type: "daterange",
        width: 80,
        label: "修改时间",
        value: [],
        timePeriod: true,
        radio: -1,
      },
    ],
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        timePeriod: true,
        radio: 1,
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "启用",
        option: "enable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "unEnable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "exprot",
        color: "white",
      },
      {
        label: "删除",
        option: "remove",
        color: "white",
        isRelaTable: true,
      },
    ],
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,

    detailData: {},
    isShowDetailPopup: false,
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            text: "系统资产编码",
            id: "systemAssetsCode",
            width: 50,
          },
          {
            text: "资产种类",
            id: "assetsType",
            width: 50,
          },
          {
            text: "设备名称",
            id: "assetsModelName",
            width: 50,
          },
          {
            text: "计量单位",
            id: "newNumUnit",
            width: 50,
          },
          {
            text: "所属品牌",
            id: "assetsBrandName",
            width: 50,
          },
          {
            text: "购置时间",
            id: "buyTime",
            width: 50,
          },
          {
            text: "型号编码",
            id: "assetsModelCode",
            width: 50,
          },
          {
            text: "使用部门负责人",
            id: "usingHeadName",
            width: 50,
          },
          {
            text: "机台号",
            id: "machineCode",
            width: 50,
          },
          {
            text: "资产类型",
            id: "assetsModelTypeName",
            width: 50,
          },
          {
            text: "制程",
            id: "processName",
            width: 50,
          },
          {
            text: "设备编号",
            id: "deviceCode",
            width: 50,
          },
          {
            text: "使用项目",
            id: "useProject",
            width: 50,
          },
          {
            text: "设备分类",
            id: "deviceType",
            width: 50,
          },
          {
            text: "存放位置",
            id: "placementLocation",
            width: 50,
          },
          {
            text: "所有权人",
            id: "ownerUserName",
            width: 50,
          },
          {
            text: "闲置原因",
            id: "idleReason",
            width: 50,
          },
          {
            text: "设备铭牌编码",
            id: "deviceNameplateCode",
            width: 50,
          },
          {
            text: "资产管理员",
            id: "assetAdminUserName",
            width: 50,
          },
          {
            text: "备注",
            id: "remark",
            width: 100,
          },
        ],
      },
    ],

    // 新增编辑弹窗
    formObj: {},
    formData: {},
    popupList: [
      {
        label: "系统资产编码",
        type: "input",
        width: 50,
        value: "",
        id: "systemAssetsCode",
      },
      {
        label: "计量单位",
        type: "loadselect",
        width: 50,
        value: "",
        selectedLabel: "",
        reviewLabel: "unitCode",
        requestObj: {
          url: "/api/trio-system/unit/page",
          method: "post",
          searchKey: "unitName",
          rlLabel: "unitCode(unitName)",
          rlValue: "u9Code",
          resultKey: "data,data,records",
        },
        id: "unitCode",
      },
      {
        label: "设备名称",
        type: "loadselect",
        width: 50,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "assetsModelName",
        requestObj: {
          url: "/api/mes-equipment-service/assets-mode/page",
          method: "post",
          searchKey: "assetsModeName",
          rlLabel: "assetsModeName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        id: "assetsModelId",
      },
      {
        label: "购置时间",
        type: "date",
        width: 50,
        value: "",
        list: [],
        id: "buyTime",
      },
      {
        label: "所属品牌",
        type: "input",
        width: 50,
        value: "",
        id: "assetsBrandName",
        disabled: true,
      },
      {
        label: "使用部门",
        id: "usingDeptId",
        type: "loadselect",
        width: 50,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "usingDeptName",
        requestObj: {
          url: "/api/trio-system/system/dept/rpc-page",
          method: "post",
          searchKey: "fullName",
          rlLabel: "fullName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "型号编码",
        type: "input",
        width: 50,
        value: "",
        id: "assetsModelCode",
        reviewValue: "assetsModelCode",
        disabled: true,
      },
      {
        label: "使用部门负责人",
        id: "usingHeadId",
        type: "loadselect",
        width: 50,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "usingHeadName",
        requestObj: {
          url: "/api/trio-user/page",
          method: "get",
          searchKey: "realName",
          rlLabel: "realName/deptName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
      },
      {
        label: "资产类型",
        type: "input",
        width: 50,
        value: "",
        id: "assetsTypeName",
        reviewValue: "assetsModelTypeName",
        disabled: true,
      },
      {
        label: "制程",
        type: "loadselect",
        width: 50,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "processName",
        requestObj: {
          url: "/api/mes-production-service/process/page",
          method: "post",
          searchKey: "processName",
          rlLabel: "processName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          isEnabledList: [1],
        },
        id: "processId",
        isNeed: false,
      },
      {
        label: "机台号",
        type: "input",
        width: 50,
        value: "",
        id: "machineCode",
        isNeed: false,
      },
      {
        label: "使用项目",
        type: "input",
        width: 50,
        value: "",
        id: "useProject",
        isNeed: false,
      },
      {
        label: "设备编号",
        type: "input",
        width: 50,
        value: "",
        id: "deviceCode",
        disabled: false,
        isNeed: false,
      },
      {
        label: "存放位置",
        type: "input",
        width: 50,
        value: "",
        id: "placementLocation",
      },
      {
        label: "设备分类",
        type: "select",
        width: 50,
        value: "",
        list: [],
        id: "deviceType",
      },
      {
        label: "资产管理部门",
        id: "assetAdminDeptId",
        type: "loadselect",
        width: 50,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "assetAdminDeptName",
        requestObj: {
          url: "/api/trio-system/system/dept/rpc-page",
          method: "post",
          searchKey: "fullName",
          rlLabel: "fullName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "所有权人",
        type: "input",
        width: 50,
        value: "",
        id: "ownerUserName",
      },
      {
        label: "资产管理员",
        id: "assetAdminUserId",
        type: "loadselect",
        width: 50,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "assetAdminUserName",
        requestObj: {
          url: "/api/trio-user/page",
          method: "get",
          searchKey: "realName",
          rlLabel: "realName/deptName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
      },
      {
        label: "设备铭牌编号",
        type: "input",
        width: 50,
        value: "",
        id: "deviceNameplateCode",
        isNeed: false,
      },
      {
        label: "闲置原因",
        type: "input",
        width: 50,
        value: "",
        id: "idleReason",
        disabled: false,
        isNeed: false,
      },
      {
        label: "资产种类",
        type: "input",
        width: 50,
        value: "",
        id: "assetsType",
        disabled: false,
      },
      {
        label: "是否启用",
        type: "radio",
        width: 50,
        value: 1,
        id: "isEnabled",
        list: [
          { label: "启用", value: 1 },
          { label: "停用", value: 0 },
        ],
        isNeed: false,
      },
      {
        isNeed: false,
        label: "备注",
        type: "textarea",
        maxlength: 100,
        width: 100,
        value: "",
        id: "remark",
      },
    ],
    relationList: [
      {
        id: "assetsModelId",
        relaList: [
          {
            relaId: "assetsBrandName",
            relaValue: "assetsBrandName",
            reviewValue: "assetsBrandName",
            disabled: true,
          },
          {
            relaId: "assetsModelCode",
            relaValue: "assetsModeCode",
            reviewValue: "assetsModelCode",
            disabled: true,
          },
          {
            relaId: "assetsTypeName",
            relaValue: "assetsTypeName",
            reviewValue: "assetsModelTypeName",
            disabled: true,
          },
        ],
      },
      {
        id: "usingDeptId",
        relaList: [
          {
            relaId: "usingHeadId",
            params: [
              {
                labelWord: "deptId",
                realWord: "rlValue",
              },
            ],
          },
        ],
      },
      {
        id: "assetAdminDeptId",
        relaList: [
          {
            relaId: "assetAdminUserId",
            params: [
              {
                labelWord: "deptId",
                realWord: "rlValue",
              },
            ],
          },
        ],
      },
    ],
    deviceTypeEnmu: [],
    isShowEdit: false,
    currentHandle: "",
    currentRowVal: {},
  }),
  computed: {
    checkTitle() {
      const titles = {
        add: "新增",
        default: "编辑",
      };
      return titles[this.currentHandle] || titles.default;
    },
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  mounted() {
    // this.getListHandle();
    this.getAllOptions();
  },
  methods: {
    operateHandle(val, type) {
      this.currentHandle = type;
      this.$validateData(val, 3);
      console.log(val);
      this.formData = type == "rowEdit" ? val : {};
      const actions = {
        add: () => {
          this.formData = {};
          this.isShowEdit = true;
        },
        rowEdit: () => {
          this.currentRowVal = val;
          this.isShowEdit = true;
        },
        remove: () => this.removeHandle(),
        exprot: () =>
          this.$exportHandle({ vm: this, params: this.searchParams }),
        view: () => this.getDetailHandle(val),
        enable: () => this.updateLineStatus(this.ids, 1, "tip.enableTip"),
        unEnable: () => this.updateLineStatus(this.ids, 0, "tip.unenableTip"),
      };

      const action = actions[type];
      if (action) action();
    },
    // 新增的辅助方法
    async updateLineStatus(ids, status, tipKey) {
      const result = await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t(tipKey)],
      });
      if (!result) return;

      const { data } = await updateStatus({ ids, isEnabled: status });
      if (data.code !== 200) return;
      this.$refs.trTable.clearSelect();
      this.$message.success(this.$t("msg.success"));
      this.searchParams.current = 1;
      this.getListHandle();
    },
    async getDetailHandle(val) {
      // const { data } = await getDetail(val.id);

      // if (data.code !== 200) return;

      // this.$validateData(data.data);

      // this.detailData = data.data;
      this.$validateData(val);
      this.detailData = val;
      this.isShowDetailPopup = true;
    },
    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },
    async getAllOptions() {
      const { ["PC-DEVICE-TYPE"]: deviceType } = await this.$fetchEnumData([
        enumData.deviceType,
      ]);
      this.deviceTypeEnmu = deviceType;
      let deviceTypePopup = this.$findByProperty(
        this.popupList,
        "id",
        "deviceType"
      );
      this.$set(deviceTypePopup, "list", deviceType);

      const { ["PC-ENABLED-LIST"]: enable } = await this.$fetchEnumData([
        enumData.isEnabledList,
      ]);
      let enableItem = this.$findByProperty(
        this.searchHideList,
        "id",
        "isEnabledList"
      );
      let enmudata = enable.map((item) => {
        return {
          ...item,
          checked: false,
        };
      });
      this.$set(enableItem, "list", enmudata);
    },
    searchHandle() {
      this.getListHandle();
    },
    async getListHandle() {
      const { data } = await getList(this.searchParams);
      if (data.code != 200) return;
      this.$validateData(data.data);
      this.tableData = data.data.records;
      this.tableData.forEach((item) => {
        item["isEnabledNameColor"] = getColor("QT", item.isEnabled);
        item.newNumUnit = `${item.unitCode}(${item.unitName})`;
      });
      this.totalNum = Number(data.data.total);
    },
    async addConfirmHandle() {
      const { data } = await add(this.formObj);
      return data.code === 200;
    },
    async removeHandle() {
      await this.$textShow({
        title: "删除",
        content: [this.$t("tip.delete")],
      });
      const { data } = await remove({ ids: this.ids });
      if (data.code !== 200) return;
      this.$message.success(this.$t("msg.success"));
      this.searchParams.current = 1;
      this.$refs.trTable.clearSelect();
      this.getListHandle();
    },
    async editHandle() {
      const { data } = await update({
        ...this.formObj,
        id: this.currentRowVal.id,
      });
      return data.code === 200;
    },
    async editConfirmHandle() {
      console.log(this.formObj, "KKKKK");
      let flag = false;

      if (this.currentHandle === "add") {
        flag = await this.addConfirmHandle();
      } else {
        flag = await this.editHandle();
      }
      if (!flag) return;
      this.$message.success(this.$t("msg.success"));
      this.isShowEdit = false;
      this.searchParams.current = 1;
      this.getListHandle();
    },
  },
};
</script>
